<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  NTag,
  NSwitch,
  NFlex,
  NAvatar,
  NSelect,
  NImage,
  NDataTable,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import { router } from '@/router'
import default_image from '@/assets/images/mz.jpg'

defineOptions({ name: '运费模板管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '商品',
  initForm: {},
  doCreate: api.creategoodsGood,
  doUpdate: api.updategoodsGood,
  doDelete: api.deletegoodsGood,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
  attributeOption: [
    {
      id: 1,
      name: '描述模板',
    },
    {
      id: 2,
      name: '规格模板',
    },
  ],
  state_option:[
    {
      value: 1,
      label: '已下架',
    },
    {
      value: 2,
      label: '上架中',
    },
  ],
  uploadAction: base_path + 'api/goods/brand/file',
  token: getToken(),
  onLevelData:[],
  brandOption:[],
  goodsType: [],
})

//获取默认会员类型
async function getcosutomer_level() {
  let ret = await api.getCustomerLevel()
  data.onLevelData = ret.data
}

function  level_format(level){
  let ret = ""
  data.onLevelData.forEach((item) => {
    if(item.value === level){
      ret = item.label
    }
  })
  return ret
}


onMounted(() => {
  getcosutomer_level()
  api.getgoodsCategoryTree().then((res) => (data.brandOption = res.data))
  api.getgoodsTypeArray().then((res) => (data.goodsType = res.data))
  $table.value?.handleSearch()
})

const columns = [
  {
    title: '+',
    width: 60,
    key: 'sku',
    align: 'center',
    type: 'expand',
    expandable: row => row.sku !== null,
    renderExpand: (row) => {
      let sku = row.sku ?? []
      let sku_columns=[
        {
          width:"auto",
          title: '规格',
          key: 'sku_name'
        },
        {
          width:"80",
          title: '封面',
          key: 'sku_cover',
          render(row2) {
            let image = row2.sku_cover[0]
            if(!image){
              image=default_image
            }
            return h(NFlex, {}, [
              h(NAvatar, {
                src: image.url,
                width: 20,
                fallbackSrc: default_image,
              }),
            ])
          },
        },
        {
          width:"80",
          title: '库存',
          key: 'sku_kc'
        },
          {
          width:"80",
          title: '疗程次数',
          key: 'can_do'
        },
        {
          width:"500",
          title: '价格',
          key: 'sku_level',
          align: 'center',
          ellipsis: { tooltip: true },
          render(row3) {
            const sku_level = row3.sku_level ?? []
            const group = []
            let level_name = ""
            for (let i = 1; i < sku_level.length; i++){
                level_name = level_format(i)
                let con = level_name+":￥"+sku_level[i]
                group.push(
                    h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '0px 3px' } }, { default: () => con })
                )
            }
            return h('span', group)
          },
        },
      ]
      return h(NDataTable, { columns: sku_columns,striped:true ,size:"small",data:sku, style: { width: '1000px',margin:'10px 10px' }  })
    }
  },
  {
    title: 'ID',
    key: 'id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '商品类型',
    key: 'type',
    align: 'center',
    width:100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () =>data.goodsType[row.type]}
      )
    },
  },
  {
    title: '类目',
    key: 'lm',
    width: '100',
    align: 'center',
    ellipsis: { tooltip: true },
  },

  {
    title: '商品名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '封面',
    key: 'cover',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {}, [
        h(NAvatar, {
          src: row.cover,
          width: 30,
          fallbackSrc: default_image,
        }),
      ])
    },
  },
  {
    title: '上架状态',
    key: 'state',
    width: '80',
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.state,
        round:false,
        loading: !!row.publishing,
        checkedValue: true,
        uncheckedValue: false,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '标签',
    key: 'tags',
    align: 'center',
    width:"120",
    ellipsis: { tooltip: true },
    render(row) {
      const tags = row.tags ?? []
      const group = []
      for (let i = 0; i < tags.length; i++)
        group.push(
            h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '0px 3px' } }, { default: () => tags[i] })
        )
      return h('span', group)
    },
  },
  {
    title: '零售价',
    key: 'price',
    width: '140',
    align: 'center',
  },
  {
    title: '库存',
    key: 'kc',
    width: '100',
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '销量',
    key: 'sale_num',
    width: '100',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '排序',
    key: 'order',
    width: '100',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  // {
  //   title: '创建时间',
  //   key: 'created_at',
  //   align: 'center',
  //   width: 'auto',
  //   ellipsis: { tooltip: true },
  // },

  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    on_edit(row)
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', { size: 16 }),
                }
            ),
            [[vPermission, 'post/api/content/category/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({ data_id: row.id }, false),
              onNegativeClick: () => {},
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/category/delete']]
                  ),
              default: () => h('div', {}, '确定删除该商品吗?'),
            }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    await api.updategoodsGood(row)
    $message?.success(row.state ? '已上架' : '已下架')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false
  } finally {
    row.publishing = false
  }
}

function on_add() {
  router.push('/goods/good_add')
}

function on_edit(row) {
  router.push({ path: '/goods/good_add', query: { id: row.id } })
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="商品管理列表">
    <template #action>
      <div>
        <NButton
            v-permission="'post/api/content/category/create'"
            class="float-right mr-15"
            type="primary"
            @click="on_add"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建商品
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getgoodsGood"
        :scroll-x="1600"
    >
      <template #queryBar>
        <QueryBarItem label="商品名称" :label-width="80">
          <NInput
              v-model:value="queryItems.name"
              clearable
              type="text"
              placeholder="请输入商品名称"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
        <QueryBarItem label="商品类目" :label-width="80">
          <NTreeSelect
              v-model:value="queryItems.category_id"
              style="width: 250px"
              :options="data.brandOption"
              clearable
              key-field="id"
              label-field="name"
              default-expand-all
              placeholder="请选商品类目"
          />
        </QueryBarItem>
        <QueryBarItem label="上架状态" :label-width="80">
          <NSelect
              v-model:value="queryItems.state"
              style="width: 150px"
              :options="data.state_option"
              clearable
              placeholder="请选上架状态"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
  </CommonPage>
</template>
